<?php

namespace app\admin\service;

use app\admin\model\Member;
use nxcsoft\excel\ExcelTools;
use think\facade\Db;

/**
 * 会员管理-服务类
 * @author 小码哥
 * @since 2020/11/15
 * Class MemberService
 * @package app\admin\service
 */
class MemberService extends BaseService
{
    /**
     * 构造函数
     * @author 小码哥
     * @since 2020/11/15
     * MemberService constructor.
     */
    public function __construct()
    {
        $this->model = new Member();
    }

    /**
     * @return array
     * @throws \think\db\exception\DbException
     * 获取列表
     */
    public function getList()
    {
        $sort = 'id desc';
        // 常规查询条件
        $param = request()->param();
        $map = [];
        if ($param) {
            // 筛选标题
            if (isset($param['name']) && $param['name']) {
                $map[] = ['name', 'like', "%{$param['name']}%"];
            }
            if (isset($param['idcard']) && $param['idcard']) {
                $map[] = ['idcard', '=', $param['idcard']];
            }
            if (isset($param['gender']) && $param['gender']) {
                $map[] = ['gender', '=', $param['gender']];
            }
            // 筛选状态
            if (isset($param['status']) && $param['status']) {
                $map[] = ['status', '=', $param['status']];
            }
            if (isset($param['examinee_number']) && $param['examinee_number']) {
                $map[] = ['examinee_number', '=', $param['examinee_number']];
            }

        }
        // 设置查询条件
        if (is_array($map)) {
            $map[] = ['mark', '=', 1];
        } elseif ($map) {
            $map .= " AND mark=1 ";
        } else {
            $map .= " mark=1 ";
        }
        $count = $this->model
            ->where($map)
            ->count();
        $ids = $this->model
            ->where($map)
            ->order($sort)
            ->page(PAGE, PERPAGE)
            ->column("id");
        $map[] = ['id', 'in', $ids];
        $field = '';
        $list = $this->model->getAllInfo($map, $field);
        if (empty($list)) {
            //获取数据总数
            //返回结果
            $message = array(
                "msg" => '操作成功',
                "code" => 0,
                "data" => $list,
                "count" => $count,
            );
            unset($list, $count, $map, $param, $ids);
            return $message;
        }
        foreach ($list as &$item) {
            if (!empty($item['file_pdf'])) {
                $item['file_pdf'] = $this->fileType($item['file_pdf']);
            }
        }
//
        //获取数据总数
        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );
        unset($list, $count, $map, $param, $ids);
        return $message;
    }

    /**
     * @param $file_pdf
     * @return array
     * 返回数组
     */
    public function fileType($file_pdf)
    {
        $filePdfArray = explode(',', $file_pdf);
        $fileArrays = [];
        foreach ($filePdfArray as $filePdf) {
            $urlParts = explode('/', $filePdf);
            // 获取最后一个部分，即文件名
            $filename = end($urlParts);
            // 使用pathinfo函数获取文件后缀
            $fileExtension = pathinfo($filename, PATHINFO_EXTENSION);
            // 创建一个包含文件后缀的数组
             array_push($fileArrays, ['url' => 'https://cdn.yfzxzjysg.top/nxcsoft/' . $filename, 'typeStr' => $fileExtension]);
        }
        return  $fileArrays;
    }

    /**
     * @return array
     * @throws \think\db\exception\DbException
     * 导出报名列表
     */
    public function exportsignup()
    {
        $sort = 'id desc';
        // 常规查询条件
        $param = request()->param();
        $map = [];
        if ($param) {
            // 筛选标题
            if (isset($param['name']) && $param['name']) {
                $map[] = ['name', 'like', "%{$param['name']}%"];
            }
            if (isset($param['idcard']) && $param['idcard']) {
                $map[] = ['idcard', '=', $param['idcard']];
            }
            if (isset($param['gender']) && $param['gender']) {
                $map[] = ['gender', '=', $param['gender']];
            }
            // 筛选状态
            if (isset($param['status']) && $param['status']) {
                $map[] = ['status', '=', $param['status']];
            }
        }
        // 设置查询条件
        if (is_array($map)) {
            $map[] = ['mark', '=', 1];
        } elseif ($map) {
            $map .= " AND mark=1 ";
        } else {
            $map .= " mark=1 ";
        }
        $ids = $this->model
            ->where($map)
            ->order($sort)
            ->column("id");
        $map[] = ['id', 'in', $ids];
        $field = '';
        $list = $this->model->getAllInfo($map, $field);
        if (empty($list)) {
            //获取数据总数
            //返回结果
            $message = array(
                "msg" => '操作成功',
                "code" => 0,
                "data" => $list,
            );
            unset($list, $count, $map, $param, $ids);
            return $message;
        }
        foreach ($list as &$item) {
            $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
        }
        //获取数据总数
        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
        );
        unset($list, $count, $map, $param, $ids);
        return $message;
    }


    /**
     * 添加或编辑
     * @return array
     * @since 2020/11/21
     * @author 小码哥
     */
    public function edit()
    {
        $params = request()->param();
        $rule = [
            'idcard|身份证号码' => 'require|idCard',
            'mobile|手机号码' => 'require|mobile',
        ];
        $validate = \think\facade\Validate::rule($rule);
        if (!$validate->check($params)) {
            return message($validate->getError(), false);
        }
        $isidcard = is_idcard($params['idcard']);
        if ($isidcard == false) {
            return message('身份证信息校验失败', false);
        }
        // 请求参数
        $data = request()->param();
        // 头像处理
        $data['password'] = get_password("123456" . $data['examinee_number']);
        return parent::edit($data); // TODO: Change the autogenerated stub
    }

    /**
     * 重置密码
     * @return array
     * @throws \think\db\exception\BindParamException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @author 小码哥
     * @since 2024/02/26
     */
    public function resetPwd()
    {
        // 获取参数
        $param = request()->param();
        // 用户ID
        $userId = getter($param, "id");
        if (!$userId) {
            return message("学生ID不能为空", false);
        }
        $userInfo = $this->model->getInfo($userId);
        if (!$userInfo) {
            return message("学生信息不存在", false);
        }
        $item = [
            'id' => $param['id'],
            'password' => get_password("123456" . $userInfo['examinee_number']),
        ];
        $result = $this->model->edit($item);
        if (!$result) {
            return message("重置密码失败", false);
        }
        return message("重置密码成功");
    }

    /**
     * 导入学员信息
     */
    public function import_user_excel()
    {
        $param = request()->param();
        $status = $param['status'];
        //接受文件
        $file = $_FILES['file']['tmp_name'];
        $indexArray = [
            'realname',
            'examinee_number',
            'idcard',
            'gender',
            'mobile',
        ];//title 数据库字段
        $resIndex = [
            'realname',
            'examinee_number',
            'idcard',
            'gender',
            'mobile',
        ];//必填字段
        $obj = new ExcelTools();
        //对应关系 防止修改数据title
        $namesArray = [
            'realname' => '姓名',
            'examinee_number' => '准考证号',
            'idcard' => '身份证号',
            'gender' => '性别',
            'mobile' => '手机号码',
        ];
        $res = $obj->SaveExcel($file, 1, $indexArray, $resIndex);
        foreach ($res[0] as $key => $value) {
            if ($namesArray[$key] != $value) {
                return message("数据格式不正确，请修改后提交", false);
            }
        }
        $sexArray = [
            '男' => 1,
            '女' => 2
        ];
        unset($res[0]);//删除表头信息
        foreach ($res as $val) {
            $isidcard = is_idcard($val['idcard']);
            if ($isidcard == false) {
                return message($val['realname'] . '的身份证信息校验失败已终止导入', false);
            }
            $isHaveId = Db::name('member')
                ->where('examinee_number', $val['examinee_number'])
                ->value('id');
            if ($isHaveId) {
                $data = [
                    'realname' => $val['realname'],
                    'examinee_number' => $val['examinee_number'],
                    'idcard' => $val['idcard'],
                    'status' => $status,
                    'gender' => $sexArray[$val['gender']],
                    'mobile' => $val['mobile'],
                    'update_time' => time(),
                    'mark' => 1,
                ];
                Db::name('member')
                    ->where('id', $isHaveId)
                    ->update($data);
            } else {
                $data = [
                    'realname' => $val['realname'],
                    'examinee_number' => $val['examinee_number'],
                    'password' => get_password("123456" . $val['examinee_number']),
                    'idcard' => $val['idcard'],
                    'gender' => $sexArray[$val['gender']],
                    'mobile' => $val['mobile'],
                    'create_time' => time(),
                    'update_time' => time(),
                    'mark' => 1,
                ];
                Db::name('member')->insert($data);
            }
        }
        return message("导入成功");
    }
}